﻿using System.ServiceModel;
using System.Text;
using System.Threading;
using System.Xml;
using NAnt.Core;
using NAnt.Core.Attributes;

namespace RemoteWorker.NantTask
{
    [TaskName("remoute_exec")]
    [CallbackBehavior(AutomaticSessionShutdown = false, IncludeExceptionDetailInFaults = true)]
    public class RemouteExecuteTask : Task, INantTask
    {
        protected override void InitializeTask(XmlNode taskNode)
        {
            base.InitializeTask(taskNode);

            _server = new ServerConnection(this);
        }

        [TaskAttribute("workerName")]
        public string WorkerName { get; set; }

        [TaskAttribute("fileName")]
        public string FileName { get; set; }

        [TaskAttribute("args")]
        public string Args { get; set; }


        protected override void ExecuteTask()
        {
            _log = new StringBuilder();

            _server.Execute(WorkerName, FileName, Args);

            while (!_done)
            {
                Thread.Sleep(10);
                lock (_lock)
                {
                    if (_log.Length > 0)
                    {
                        Log(Level.Info, _log.ToString());
                        _log.Length = 0;
                    }
                }
            }
            Log(Level.Info, "Done");
        }

        public void Log(string message)
        {
            lock (_lock)
            {
                _log.AppendLine(message);
            }
        }

        public void Complete(int exitCode)
        {
            Log(string.Format("exit code: {0}", exitCode));
            _done = true;
        }

        private ServerConnection _server;
        private bool _done;
        private StringBuilder _log;
        private object _lock = new object();
    }
}